﻿using System;
using System.Data;
using System.Data.Odbc;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using BTS.Constant;
using BTS.DB;
using BTS.Entity;
using BTS.Util;

namespace BTS.Page
{


    public partial class TeacherManage : System.Web.UI.Page
    {
        public string actPage = "list";
        public string targetID = "0";

        public StringBuilder outBuf = new StringBuilder();
        public StringBuilder outBuf2 = new StringBuilder();

        public DateTime startDate;
        public DateTime endDate;
        public string branchID;
        public string branchName;
        public Registration[] reg;
        public Branch[] branchList;

        public int[] numPaidMethod = new int[4];
        public int[] sumCostByPaidMethod = new int[4];
        public int sumAllCost = 0;

        public string errorText = "";
        public CultureInfo ci = new CultureInfo("en-US");
        public Logger log = Logger.GetLogger(Config.MAINLOG);
    //    protected System.Web.UI.HtmlControls.HtmlInputFile portrait;
  

        protected void Page_Load(object sender, EventArgs e)
        {
            // Authentication
            string redirect = VerifyAA.Verify(Session
                , Request
                , Response
                , "NoRight.aspx");

            // Collect paramters
            actPage = Request.Form.Get("actPage");
            if (actPage == null) actPage = Request["actPage"];
            targetID = Request.Form.Get("targetID");
            if (targetID == null) targetID = Request["targetID"];

            // log
            log.StampLine(Logger.DETAILED, "Request [" + Request["ASP.NET_SessionId"] + "][" + Request.RawUrl + "][actPage=" + actPage + "&targetID=" + targetID + "]");
            log.StampLine(Logger.DEBUG, "Param [" + Request["ASP.NET_SessionId"] + "][" + Request.Params.ToString() + "]");


                string sdate = Request.Form.Get("start_date");
                string edate = Request.Form.Get("end_date");
                branchID = Request.Form.Get("branch_id");

                // Verify branch
                if (branchID == null)
                {
                    AppUser user = (AppUser)Session[SessionVar.USER];
                    if (!user.IsAdmin()) branchID = user._branchID.ToString(); else branchID = "0";
                }

            
                if ((actPage == null) || (actPage.Trim().Length==0) || (actPage.Equals("report")))
                {
                    LoadData(sdate, edate, branchID);
                    // Presentation
                    DoInitPrintDailyRegistration();
                    Session[SessionVar.PRINT_INFO] = new StringBuilder(outBuf.ToString());
                    DoReportDailyRegistration();
                }

        }

        protected void LoadData(string startDateString, string endDateString, string branchID)
        {
            DBManager db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD);
            db.Connect();

            // Load branchlist
            branchList = Branch.LoadListFromDBCustom(db, "SELECT * from branch ORDER BY branch_id ");

            if (startDateString != null)
            {
                string[] s = startDateString.Split('/');

                startDate = new DateTime(Int32.Parse(s[2]), Int32.Parse(s[1]), Int32.Parse(s[0]));
            }
            else
            {
                startDate = DateTime.Today;
            }

            if (endDateString != null)
            {
                string[] s = endDateString.Split('/');
                endDate = new DateTime(Int32.Parse(s[2]), Int32.Parse(s[1]), Int32.Parse(s[0]));
                endDate = endDate.AddHours(23).AddMinutes(59).AddSeconds(59);
            }
            else
            {
                endDate = DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59);
            }

            // Get branch name
            if (branchID.Equals("0"))
            {
                branchName = "ทุกสาขา";
            }
            else
            {
                Branch b = new Branch();
                b.LoadFromDB(db, " branch_id=" + branchID);
                branchName = b._branchName;
            }


            string selectSQl = "SELECT rg.*, s.firstname as student_firstname, s.surname as student_surname, c.bts_course_id as bts_course_id, c.course_name as course_name FROM registration rg, student s, course c ";
            string whereSQL = " WHERE rg.student_id=s.student_id AND rg.course_id=c.course_id "
                                + "AND rg.regis_date between '" + startDate.ToString("yyyy/MM/dd HH:mm:ss", ci) + "' and '" + endDate.ToString("yyyy/MM/dd HH:mm:ss", ci) + "' "
                                + ((!branchID.Equals("0")) ? " AND rg.branch_id=" + branchID : "")
                                + " ORDER BY rg.regis_id ";
            reg = Registration.LoadListFromDBCustom(db, selectSQl + whereSQL);
            db.Close();


            for (int i = 0; i < reg.Length; i++)
            {
                numPaidMethod[reg[i]._paidMethod]++;
                sumCostByPaidMethod[reg[i]._paidMethod] += reg[i]._discountedCost;
                sumAllCost += reg[i]._discountedCost;
            }
        }

        protected void DoInitPrintDailyRegistration()
        {
            outBuf = new StringBuilder();

            // Generate HTML content
            int maxpg = reg.Length / Config.PAGE_BREAK_DAILY_REG_REPORT;
            if (maxpg < 1) { maxpg = 1; }
            else if (reg.Length % Config.PAGE_BREAK_DAILY_REG_REPORT > 0) { maxpg++; }

            for (int j = 0; j < maxpg; j++)
            {
                int idx1 = j * Config.PAGE_BREAK_DAILY_REG_REPORT;
                int idx2 = (j+1) * Config.PAGE_BREAK_DAILY_REG_REPORT;
                if (idx2>reg.Length) idx2=reg.Length;

                // header table
                StringBuilder contentTxt = new StringBuilder();
                contentTxt.AppendLine("<tr bgcolor=\"#CAE8EA\">");
                contentTxt.AppendLine("<th scope=\"col\" align=center width=\"30px\" NOWRAP><font size=2><b>ลำดับ</b></font></th>");
                contentTxt.AppendLine("<th scope=\"col\" align=center width=\"80px\"><font size=2><b>วัน-เวลา</b></font></th>");
                contentTxt.AppendLine("<th scope=\"col\" align=center width=\"150px\"><font size=2><b>นักเรียน</b></font></th>");
                contentTxt.AppendLine("<th scope=\"col\" align=center width=\"300px\"><font size=2><b>คอร์ส</b></font></th>");
                contentTxt.AppendLine("<th scope=\"col\" align=center width=\"100px\"><font size=2><b>ราคาจ่าย</b></font></th>");
                contentTxt.AppendLine("<th scope=\"col\" align=center width=\"70px\"><font size=2><b>วิธีชำระเงิน</b></font></th>");
                contentTxt.AppendLine("<th scope=\"col\" align=center width=\"100px\"><font size=2><b>รหัสลงทะเบียน</b></font></th>");
                contentTxt.AppendLine("</tr>");

                // content
                for (int i = idx1; i < idx2; i++)
                {
                    //numPaidMethod[reg[i]._paidMethod]++;
                    //sumCostByPaidMethod[reg[i]._paidMethod] += reg[i]._discountedCost;
                    //sumAllCost += reg[i]._discountedCost;

                    contentTxt.AppendLine("<tr>");
                    contentTxt.AppendLine("<td><font size=2>" + (i + 1) + "</font></td>");
                    contentTxt.AppendLine("<td align=center><font size=2>" + reg[i]._regisdate.ToString("dd/MMyyyy HH:mm", ci) + "</font></td>");
                    contentTxt.AppendLine("<td><font size=2>" + Student.GetStudentID(reg[i]._studentID) + " " + reg[i]._studentFirstname + " " + reg[i]._studentSurname + "</font></td>");
                    contentTxt.AppendLine("<td><font size=2>" + reg[i]._btsCourseID + " " + reg[i]._courseName + "</font></td>");
                    contentTxt.AppendLine("<td align=center><font size=2>" + StringUtil.Int2StrComma(reg[i]._discountedCost) + "</font></td>");
                    contentTxt.AppendLine("<td align=center><font size=2>" + Registration.GetPaidMethodText(reg[i]._paidMethod.ToString()) + "</font></td>");
                    contentTxt.AppendLine("<td align=center><font size=2>" + Registration.GetRegistrationID(reg[i]._regisID) + "</font></td>");
                    contentTxt.AppendLine("</tr>");
                }

                // summary table
                StringBuilder summaryTxt = new StringBuilder();
                if (j == (maxpg - 1))
                {

                        
                    summaryTxt.AppendLine("<br>");
                    summaryTxt.AppendLine("<table width=\"300px\" align=right border=1 cellpadding=0 cellspacing=0 bordercolor=\"#C1DAD7\" bgcolor=\"#FFFFFF\">");
                    summaryTxt.AppendLine(" <tr bgcolor=\"#CAE8EA\"><td colspan=3 align=center><b>สรุปยอด</b></td></tr>");
                    summaryTxt.AppendLine(" <tr bgcolor=\"#CAE8EA\"><td width=\"100px\" align=center><b>วิธีชำระเงิน</b></td><td width=\"100px\" align=center><b>รายการ</b></td><td width=\"100px\" align=center><b>ยอดรวม(บาท)</b></td></tr>");
                      for (int k=0;k<numPaidMethod.Length;k++) 
                      {
                          summaryTxt.AppendLine("<tr bgcolor=\"#FFFFFF\">");
                          summaryTxt.AppendLine("<td align=center>"+Registration.GetPaidMethodText(k.ToString())+"</td>");
                          summaryTxt.AppendLine("<td align=center>"+numPaidMethod[k]+"</td>");
                          summaryTxt.AppendLine("<td align=right>"+StringUtil.Int2StrComma(sumCostByPaidMethod[k])+"&nbsp&nbsp</td>");
                          summaryTxt.AppendLine("</tr>");
                      }
                    summaryTxt.AppendLine("<tr bgcolor=\"#FFFFFF\">");
                    summaryTxt.AppendLine("<td align=center><b>รวมทั้งสิ้น</b></td>");
                    summaryTxt.AppendLine("<td align=center><b>"+ reg.Length +"</b></td>");
                    summaryTxt.AppendLine("<td align=right><b>"+ StringUtil.Int2StrComma(sumAllCost) +"</b>&nbsp&nbsp</td>");
                    summaryTxt.AppendLine("</tr>");
                    summaryTxt.AppendLine("</table>");
                }


                TextReader reader = new StreamReader(Config.PATH_APP_ROOT + "\\template\\report_daily_registration_print.htm");
                String templateContent = reader.ReadToEnd();
                reader.Close();

                String htmlContent =
                    String.Format(templateContent
                        , branchName
                        , StringUtil.ConvertYearToEng(startDate, "dd/MM/yyyy")
                        , StringUtil.ConvertYearToEng(endDate, "dd/MM/yyyy")
                        , contentTxt.ToString()
                        , summaryTxt.ToString()
                        );

                outBuf.AppendLine(htmlContent);
                
                // Add page break for all not last page
                
                if (j < maxpg - 1)
                {
                    outBuf.AppendLine("<P CLASS=\"pagebreakhere\">&nbsp</p>");
                }
                
            }
        }



        protected void DoReportDailyRegistration()
        {
            outBuf = new StringBuilder();

            // Presentaion
            string[,] bgclass = new string[,] { { "class=\"spec\"", "class=\"td1\"" }, { "class=\"specalt\"", "class=\"alt\"" } };
            for (int i = 0; i < reg.Length; i++)
            {
                //numPaidMethod[reg[i]._paidMethod]++;
                //sumCostByPaidMethod[reg[i]._paidMethod] += reg[i]._discountedCost;
                //sumAllCost += reg[i]._discountedCost;

                string studentTxt = "<a href=\"StudentManage.aspx?actPage=view&targetID=" + reg[i]._studentID + "\">" + Student.GetStudentID(reg[i]._studentID) + " " + reg[i]._studentFirstname + " " + reg[i]._studentSurname + "</a>";
                string courseTxt = "<a href=\"CourseManage.aspx?actPage=view&targetID="+reg[i]._courseID+"\">" + reg[i]._btsCourseID + " " + reg[i]._courseName + "</a>";
                outBuf.Append("<tr>");
                outBuf.Append("<th scope=\"row\" abbr=\"Model\" " + bgclass[i % 2, 0] + ">" + (i + 1) + "</th>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + "  >" + reg[i]._regisdate.ToString("dd/MMyyyy HH:mm", ci) + "&nbsp</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + "  >" + studentTxt + "&nbsp</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + "  >" + courseTxt + "&nbsp</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + " align=right >" + StringUtil.Int2StrComma(reg[i]._discountedCost) + "&nbsp</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + "  >" + Registration.GetPaidMethodText(reg[i]._paidMethod.ToString()) + "&nbsp</td>");
                outBuf.Append("<td " + bgclass[i % 2, 1] + " align=center  >" + Registration.GetRegistrationID(reg[i]._regisID) + "&nbsp</td>");
                outBuf.Append("</tr>\n");
            }

        }


    }
}
